﻿/*
COPYRIGHT (C) 2008 EPISERVER AB

THIS FILE IS PART OF SCRUM DASHBOARD.

SCRUM DASHBOARD IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUM DASHBOARD IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUM DASHBOARD. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.ServiceModel.Syndication;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using ScrumDashboard.Library;
using ScrumDashboard.Notification;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using ScrumDashboard.Library.Entities;
using ScrumDashboard.Library.Model;
using ScrumDashboard.Library.Tfs;

namespace ScrumDashboard
{
    public class rss : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string project = context.Request.QueryString["project"];
            if (String.IsNullOrEmpty(project))
            {
                if (context.Request.Cookies["LastViewedProject"] != null && !String.IsNullOrEmpty(context.Request.Cookies["LastViewedProject"].Value))
                {
                    project = context.Request.Cookies["LastViewedProject"].Value;
                    context.Response.Redirect("rss.ashx?project=" + context.Server.UrlEncode(project));
                    return;
                }

                throw new Exception("No project specified");
            }

            context.Response.ContentType = "text/xml";


            SyndicationFeed feed = new SyndicationFeed(project + " Product Backlog (Scrum Dashboard)","",new Uri(ConfigurationManager.AppSettings["tfsWebAccess"] + "ScrumDashboard"));

            TfsManager tfs = new TfsManager();

            List<SyndicationItem> items = new List<SyndicationItem>();

            foreach (WorkItemEvent d in DBHelper.GetWorkItemEvents(project, "Product Backlog Item", 50, TimeSpan.FromDays(30)))
            {
                ProductBacklogItem backlog = tfs.GetProductBacklog(d.WorkItemId, d.RevisionId);
                SyndicationItem item = new SyndicationItem(CreateTitle(d,backlog),CreateDescription(context,backlog),new Uri(ConfigurationManager.AppSettings["tfsWebAccess"] + "wi.aspx?id=" + backlog.Id.ToString()),d.WorkItemId + "-" + d.RevisionId,backlog.Changed);
                item.ElementExtensions.Add("author", "", backlog.ChangedBy);
                items.Add(item);
            }

            feed.Items = items;

            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            XmlWriter writer = new XmlTextWriter(sw);
            feed.SaveAsRss20(writer);
            writer.Flush();
            writer.Close();
            sw.Flush();
            sw.Close();
            context.Response.Write(sb.ToString());
        }

        private string CreateTitle(WorkItemEvent d, ProductBacklogItem wi)
        {
            if (d.ChangedState)
                return wi.State.ToUpper() + ": " + wi.Title;
            else
                return (d.IsNew ? "NEW: " : "UPDATED: ") + wi.Title;

        }

        private string CreateDescription(HttpContext context, ProductBacklogItem wi)
        {
            StringBuilder b = new StringBuilder();
            b.Append(TextEncode(context,wi.Description));
            b.Append("<br />");
            b.Append("<br />");
            b.Append("<strong>Sprint:</strong> " + wi.SprintName);
            b.Append("<br />");
            b.Append("<strong>Team:</strong> " + wi.Team);
            b.Append("<br />");
            b.Append("<strong>Status:</strong> " + wi.State);
            b.Append("<br />");
            b.Append("<strong>Work remaining:</strong> " + wi.WorkRemaining + " hr(s)");
            b.Append("<br />");
            b.Append("<strong>Estimated effort:</strong> " + wi.EstimatedEffort);
            b.Append("<br />");
            b.Append("<strong>Delivery order:</strong> " + wi.DeliveryOrder);
            b.Append("<br />");
            return b.ToString();
        }

        private string TextEncode(HttpContext context, string text)
        {
            if (String.IsNullOrEmpty(text))
                return String.Empty;

            text = context.Server.HtmlEncode(text);
            text = text.Replace("\n", "<br />");

            return text;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
